<script>
  let callbacks = new Map()
  let reactivities = new Map()
  let usedReactivties = []
  let object = {
    a: { c: 2 },
    b: 2
  }
  let po = reactive(object)

  effect(() => {
    console.log(po.a.c,'effect')
  })
  function effect(callback) {
    // callbacks.push(callback)
    // 清空
    usedReactivties = []
    callback()
    console.log(usedReactivties);
    for (const reactivity of usedReactivties) {
      if (!callbacks.has(reactivity[0])) {
        callbacks.set(reactivity[0], new Map())
      }
      if (!callbacks.get(reactivity[0]).has(reactivity[1])) {
        callbacks.get(reactivity[0]).set(reactivity[1], [])
      }
      callbacks.get(reactivity[0]).get(reactivity[1]).push(callback)
    }
  }

  function reactive(obj) {
    if (reactivities.has(obj))
      return reactivities.get(obj)
    let proxy = new Proxy(obj, {
      set(obj, prop, val) {
        obj[prop] = val
        if (callbacks.has(obj))
          if (callbacks.get(obj).get(prop))
            for (const callback of callbacks.get(obj).get(prop)) {
              callback()
            }
        return obj[prop]
      },
      get(obj, prop) {
        // console.log(obj, prop)
        usedReactivties.push([obj, prop])
        if (typeof obj[prop] === "object") return reactive(obj[prop])
        return obj[prop]
      }
    })
    reactivities.set(obj, proxy)
    return proxy
  }
</script>
